layui.use(['table', 'admin', 'ax', 'func','laydate','formSelects', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var form = layui.form;


    var formSelects = layui.formSelects;
    formSelects.config('selTag', {
        searchUrl: Feng.ctxPath + "/enums/userTags",
        keyName: 'name',
        keyVal: 'id'
    });

    /**
     * 用户管理
     */
    var NanUser = {
        tableId: "nanUserTable"
    };


    var laydate = layui.laydate;
    laydate.render({
        elem: '#beginTime' //指定元素
    });
    laydate.render({
        elem: '#endTime' //指定元素
    });
    var enumAjax = new $ax(Feng.ctxPath + "/enums/commonStatus");
    var enumRes = enumAjax.start();
    var projects = enumRes.data;
    var html = "";
    for(var key in projects){
        html += '<option value="'+key+'">'+projects[key]+'</option>'
    }
    $("#status").append(html);

    var sexAjax = new $ax(Feng.ctxPath + "/enums/sexTypes");
    var sexRes = sexAjax.start();
    var sexProjects = sexRes.data;
    var sexHtml = "";
    for(var key in sexProjects){
        sexHtml += '<option value="'+key+'">'+sexProjects[key]+'</option>'
    }
    $("#sex").append(sexHtml);

    form.render('select');

    /**
     * 初始化表格的列
     */
    NanUser.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {align: 'center', toolbar: '#tableBar', title: '操作', width: 150},
            {field: 'id', sort: true, title: '用户ID'},
            {field: 'email', sort: false, title: '电子邮箱'},
            {field: 'tagStr', sort: false, title: '标签'},
            {field: 'sellerId', sort: false, title: '运营组ID'},
            {field: 'statusStr', sort: false, title: '状态'},
            {field: 'deviceCode', sort: false, title: '设备码'},
            {field: 'sexStr', sort: false, title: '性别'},
            {field: 'nickName', sort: false, title: '昵称'},
            {field: 'avatar', sort: false, title: '头像', templet: '<div><img src="{{Feng.cdn}}{{d.avatar}}" alt="" /></div>'},
            {field: 'birthday', sort: false, title: '生日'},
            {field: 'country', sort: false, title: '国家'},
            {field: 'device', sort: false, title: '登录设备'},
            {field: 'chatConditionStr', sort: false, title: '是可以私信'},
            {field: 'isAllowedAdd', sort: false, title: '是否允许加好友', templet: '<div>{{d.isAllowedAdd? "是": "否"}}</div>'},
            {field: 'isOfficial', sort: false, title: '是否官方账号', templet: '<div>{{d.isOfficial? "是": "否"}}</div>'},
            {field: 'isVip', sort: false, title: '是否SVIP', templet: '<div>{{d.isVip? "是": "否"}}</div>'},
            {field: 'registerIp', sort: false, title: '注册IP'},
            {field: 'createTime', sort: false, title: '创建时间'},
            {field: 'updateTime', sort: false, title: '更新时间'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    NanUser.search = function () {
        var queryData = {};

        queryData['id'] = $('#id').val();
        queryData['status'] = $('#status').val();
        queryData['email'] = $('#email').val();
        queryData['sex'] = $('#sex').val();
        queryData['nickName'] = $('#nickName').val();
        queryData['tag'] = $('input[name=tagId]').val();
        queryData['beginTime'] = $('#beginTime').val();
        queryData['endTime'] = $('#endTime').val();

        table.reload(NanUser.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 跳转到添加页面
     */
    NanUser.jumpAddPage = function () {
        window.location.href = Feng.ctxPath + '/nanUser/add'
    };

    /**
    * 跳转到编辑页面
    *
    * @param data 点击按钮时候的行数据
    */
    NanUser.jumpEditPage = function (data) {
        window.location.href = Feng.ctxPath + '/nanUser/edit?id=' + data.id
    };

    /**
     * 导出excel按钮
     */
    NanUser.exportExcel = function (clos) {
        var id = $("#id").val();
        var status = $('#status').val();
        var email = $('#email').val();
        var sex = $('#sex').val();
        var nickName = $('#nickName').val();
        var tagId = $('input[name=tagId]').val();
        var beginTime = $('#beginTime').val();
        var endTime = $('#endTime').val();
        var str = "";
        if(id !== ""){
            str += "&id=" + id;
        }
        if(status !== ""){
            str += "&status=" + status;
        }
        if(email !== ""){
            str += "&email=" + email;
        }
        if(sex !== ""){
            str += "&sex=" + sex;
        }
        if(nickName !== ""){
            str += "&nickName=" + nickName;
        }
        if(tagId !== ""){
            str += "&tag=" + tagId;
        }
        if(beginTime !== ""){
            str += "&beginTime=" + beginTime;
        }
        if(endTime !== ""){
            str += "&endTime=" + endTime;
        }
        if(clos) clos = clos.substring(1);
        window.location.href = Feng.ctxPath + "/nanUser/export?filter=" + clos + str;
    };

    $('#btnSetTag').click(function () {
        var checkRows = table.checkStatus(NanUser.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要添加标签的用户");
            return;
        }
        var ids = [];
        checkRows.data.forEach((data) => {
            var userId = data.id;
            if(!ids.includes(userId)){
                ids.push(userId);
            }
        });
        func.open({
            title: '添加标签',
            content: Feng.ctxPath + '/nanUser/add?ids=' + ids.toString(),
            tableId: NanUser.tableId
        });
    });

    $('#btnRemoveTag').click(function () {
        var checkRows = table.checkStatus(NanUser.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要移除标签的用户");
            return;
        }
        var ids = [];
        checkRows.data.forEach((data) => {
            var userId = data.id;
            if(!ids.includes(userId)){
                ids.push(userId);
            }
        });
        func.open({
            title: '移除标签',
            content: Feng.ctxPath + '/nanUser/add?r=1&ids=' + ids.toString(),
            tableId: NanUser.tableId
        });
    });

    window.exportUserExcel = function(clos){
        NanUser.exportExcel(clos)
    }

    // 导出excel
    $('#btnExp').click(function () {
        admin.open({
            id: 'chooseCols',
            type: 2,
            area: '650px',
            title: '选择导出列',
            shade: 0,
            content: Feng.ctxPath + '/jump/user/chooseCols'
        });
    });

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    NanUser.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/nanUser/delete", function (data) {
                Feng.success("重置密码成功!");
                table.reload(NanUser.tableId);
            }, function (data) {
                Feng.error("重置密码失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否确定重置密码?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + NanUser.tableId,
        url: Feng.ctxPath + '/nanUser/list',
        page: true,
        limit: 20,
        height: "full-158",
        cellMinWidth: 100,
        cols: NanUser.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        NanUser.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

    NanUser.jumpAddPage();

    });

    table.on('sort('+NanUser.tableId+')', function(obj){
            table.reload(NanUser.tableId, {
                initSort: obj,
                where: {
                    field: obj.field.replace(/([A-Z])/g,"_$1").toLowerCase()
                    ,order: obj.type
                }
            });
        });

    // 工具条点击事件
    table.on('tool(' + NanUser.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            NanUser.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            NanUser.onDeleteItem(data);
        }
    });
});
